<?php

	class supplieProducts {
		

		function supplieProducts() {
			global $admin;

			//if(empty($_SESSION["managerid"])) $admin->login();
		}
		
		function index() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("products_view")) return;
			//var_dump($smarty->_tpl_vars);
			$smarty->assign("suppliers",$this->_getsupplierlist());
			if($_GET['setYs']==1){
				$params=$_GET;
				$sqlstr = "select hsp.*,hps.pid,hps.pname,hps.spec,hps.pic from {$config->db_prefix}products AS hsp LEFT JOIN  haiou_product_sku AS hps ON hps.id=hsp.product_sku_id where 1=1";
				if (!empty($params['product_id'])) $sqlstr .= " and hps.pid in(".trim($params['product_id']).")";
				if (isset($params['keywords']) && !empty($params['keywords'])){
					$sqlstr .= " and hps.pname like ". $db->qstr("%".$params['keywords']."%");
				}
					
				if (!empty($params['lprice'])) $sqlstr .= " and hsp.pricebuy>=". $db->qstr($params['lprice']);
				if (!empty($params['hprice'])) $sqlstr .= " and hsp.pricebuy<=". $db->qstr($params['hprice']);
					
				if (!empty($params['lstocks'])) $sqlstr .= " and hsp.stocks>=". $db->qstr($params['lstocks']);
				if (!empty($params['hstocks'])) $sqlstr .= " and hsp.stocks<=". $db->qstr($params['hstocks']);
					
				if (!empty($params['lvirstocks'])) $sqlstr .= " and hsp.canbuyout>=". $db->qstr($params['lvirstocks']);
				if (!empty($params['hvirstocks'])) $sqlstr .= " and hsp.canbuyout<=". $db->qstr($params['hvirstocks']);
					
				if (!empty($params['lwaringnum'])) $sqlstr .= " and hsp.shopwarningnum>=". $db->qstr($params['lwaringnum']);
				if (!empty($params['hwaringnum'])) $sqlstr .= " and hsp.shopwarningnum<=". $db->qstr($params['hwaringnum']);
echo $sqlstr;
			}
				
				
			
			
			if(!empty($segment[1])) {
				include_once("mod.classes.php");
				$c = new classes();
				$paths = $c->_getpaths($segment[1]);
				$smarty->assign("paths", $paths);
			}
		}


		function create() {
			
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("products_create")) return;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="create") {
				if(empty($_POST["product"])) $errors["empty_product"] = true;
				if(empty($_POST["pricebuy"])) $errors["empty_pricebuy"] = true;
				if(empty($_POST["supplier"])) $errors["empty_supplier"] = true;
				if(empty($_POST["currency_unit"])) $errors["empty_currency_unit"] = true;

				if(empty($errors)) {
					$pricebuy = $db->qstr($_POST["pricebuy"]);
					$currency_unit = $_POST['currency_unit'];
					$productid = $_POST['productid'];
					$supplierid = $_POST['supplier'];
					$shopid = $_POST['shopid'];
					$sbarcode = $_POST['sbarcode'];
					$is_default = $_POST["is_default"];
					$stock = $_POST["stock"];
					$stock_base = $_POST["stock_base"];
					$status = $_POST["status"];
					
					//查看该产品是否已在此供应商
					$sql = "select id from {$config->db_prefix}supplie_products where product_sku_id={$productid} and supplieid={$supplierid} and shopid={$shopid} limit 1";
					$pInfo = $db->getRow($sql);
					if(!empty($pInfo) && $pInfo['id']>0){
					    exit('此产品在该供应商中已存在');
					}

					if($is_default == 1){//如果默认，则把此商品的其他供应商不默认
					    $sql = "update {$config->db_prefix}supplie_products set is_default=0 where product_sku_id={$productid} and shopid={$shopid}";
					    $db->execute($sql);
					}
					
					$sqlstr = "insert into {$config->db_prefix}supplie_products (supplieid, pricebuy, currency_unit, shopid, product_sku_id, sbarcode, is_default, stock_base_num, stock, status) values ($supplierid, $pricebuy, '$currency_unit', $shopid, $productid, '$sbarcode',$is_default,$stock_base,$stock,$status)";
					$result = $db->execute($sqlstr);
					
					
					if($result){
					    if($status == -3){
					        $res = $this->updateMsProductsSupplier($productid, $shopid);
					    }
					    
					    header("location:{$config->site_admin}m=inventory&s=supplieProducts.php");
					}
						
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
			$smarty->assign("myclasses",$this->_gettree());
			$smarty->assign("suppliers",$this->_getsupplierlist());
			//货币单位
			$sql = "select * from haiou_currency_info order by id";
			$currency_info = $db->GetArray($sql);
				
			$smarty->assign("currency_unit_arr",$currency_info);
		}
		
		function modify() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("products_modify")) return;
			
			if(!empty($_POST["action"]) && $_POST["action"]=="modify") {
 				if(empty($_POST["product"])) $errors["empty_product"] = true;
				if(empty($_POST["pricebuy"])) $errors["empty_pricebuy"] = true;
				if(empty($_POST["supplier"])) $errors["empty_supplier"] = true;

				if(empty($errors)) {
				    $id = $db->qstr($_POST["id"]);
				    $productid = $_POST['productid'];
					$pricebuy = $db->qstr($_POST["pricebuy"]);
					$currency_unit = $_POST['currency_unit'];
					$supplierid = $_POST['supplier'];
					$shopid = $_POST['shopid'];
					$sbarcode = $_POST['sbarcode'];
					$is_default = $_POST["is_default"];
					$stock_base = $_POST["stock_base"];
					$stock = $_POST["stock"];
					$status = $_POST["status"];
					
					//检查是否修改了供应商
					$sql = "select supplieid,shopid from {$config->db_prefix}supplie_products where id={$id}";
					$supplierInfo = $db->getRow($sql);
					if($supplierid != $supplierInfo['supplieid']){
					    $res = $this->updateMsProductsSupplier($productid, $supplierInfo['shopid']);
					}
					
					if($is_default == 1){//如果默认，则把此商品的其他供应商不默认
					    $sql = "update {$config->db_prefix}supplie_products set is_default=0 where product_sku_id={$productid} and shopid={$shopid}";
					    $db->execute($sql);
					}
					
					$sqlstr = "update {$config->db_prefix}supplie_products set pricebuy=$pricebuy,currency_unit='{$currency_unit}',supplieid={$supplierid},shopid={$shopid},sbarcode='{$sbarcode}',is_default={$is_default},stock_base_num={$stock_base},stock={$stock},status={$status} where id=$id";
					$result = $db->execute($sqlstr);
					
					/********检查最低真实采购单价min_realpricebuy和avg_realpricebuy字段是否为0，如果为0则更新为pricebuy字段*********/
					$sqlspec = "select min_realpricebuy,avg_realpricebuy from {$config->db_prefix}supplie_products where id=$id";
					$min_avg_realpricebuy = $db->getRow($sqlspec);
					$updateStr = "";
					if(!($min_avg_realpricebuy['min_realpricebuy']>0)){
						$updateStr .=" min_realpricebuy=pricebuy,";
					}
					if(!($min_avg_realpricebuy['avg_realpricebuy']>0)){
						$updateStr .=" avg_realpricebuy=pricebuy,";
					}
					if($updateStr!=''){
						$updateStr = trim($updateStr,",");
						$sqlstr = "update {$config->db_prefix}supplie_products set {$updateStr} where id=$id";
						$db->execute($sqlstr);
					}
					/*****************/
					
					if($result){
					    if($status == -3){
					        $res = $this->updateMsProductsSupplier($productid, $shopid);
					    }
					    
					    header("location:".(empty($_POST["referer"])?"{$config->site_admin}m=inventory&s=supplieProducts.php":$_POST["referer"]));
					}
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
			
			//货币单位
			$sql = "select * from haiou_currency_info order by id";
			$currency_info = $db->GetArray($sql);
			
			$smarty->assign("currency_unit_arr",$currency_info);
			$smarty->assign("myclasses",$this->_gettree());
			$smarty->assign("suppliers",$this->_getsupplierlist());
		}


		function remove() {
			global $db, $segment, $config, $admin;
			//if(!$admin->rights("products_delete")) return;

			$id = $db->qstr($_GET['id']);
			$sqlstr = "delete from {$config->db_prefix}supplie_products where id=$id";
			$result = $db->execute($sqlstr);
			if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=supplieProducts.php":$_SERVER['HTTP_REFERER']));
		}
		
		private function _gettree($id=0){
		    global $db, $config;
		    $tree =array();
		    $tree_info=$db->GetArray("select * from {$config->db_prefix}classes where parentid=$id");
		    if (empty($tree_info))return null;
		    //var_dump($tree_info);
		    foreach ($tree_info as $value) {
		        $tree[$value['id']]=$value;
		        if($children=$this->_gettree($value['id'])){
		            $tree[$value['id']]['children']=$children;
		        }
		        if ($value['id']==$_GET['id']){
		            $this->parentid=$value['parentid'];
		        }
		    }
		    return $tree;
		}


		private function _getsupplierlist(){
			global $db, $config;
			$list = array();
			$list = $db->GetArray("select * from {$config->db_prefix}suppliers");
			return $list;
		}

		/**
		 * 供应商产品下架或者更改供应商则把产品对应的（现货，保税，直邮）设置为不支持
		 * @param unknown $skuId
		 * @param unknown $shopId
		 */
		private function updateMsProductsSupplier($skuId,$shopId){
		    global $db, $config;
		    
		    if($skuId>0 && $shopId>0){
		        //查找仓库类型
		        $sql = "select type from {$config->db_prefix}shops where id={$shopId}";
		        $shop = $db->getRow($sql);
		        if(!empty($shop) && $shop['type']>0){
		            $set = "";
		            switch ($shop['type']) {
		                case 1://现货
		                    $set = " `ms_stock_supplierid`=-1 ";
		                    break;
		                case 2://保税
		                    $set = " `ms_entrepot_supplierid`=-1 ";
		                    break;
		                case 3://直邮
		                    $set = " `ms_direct_supplierid`=-1 ";
		                    break;
	                    default:
	                        break;
		            }
		            
		            if(!empty($set)){
		                $sql = "update haiou_product_sku set {$set} where id={$skuId}";
		                $db->execute($sql);
		                
		                return true;
		            }
		        }
		    }
		    
		    return false;
		}

}
?>